package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dao.SetmealDao;
import com.itheima.dao.SetmealDishDao;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.pojo.SetmealDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    SetmealService setmealService;

    @Autowired
    SetmealDao setmealDao;

    @Autowired
    CategoryService categoryService;

    @Autowired
    SetmealDishDao setmealDishDao;

    @Autowired
    DishService dishService;

    //分页查询+条件查询
    @GetMapping("/page")
    //参数以k:v格式转发，不用加注解
    public R<Map> SelectPage(Integer page, Integer pageSize, String name) {
        Page<Setmeal> categoryPage = new Page<Setmeal>(page, pageSize);
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Setmeal::getName, name);
        Page<Setmeal> setmealPage = setmealService.page(categoryPage, wrapper);
        Integer total = Math.toIntExact(setmealPage.getTotal());//多少条数据
        List<Setmeal> records = setmealPage.getRecords();
        HashMap map = new HashMap();//从套餐表中的数据和category中查询出来的类名
        map.put("total", total);
        ArrayList<SetmealDto> setmealList = new ArrayList<>();
        for (Setmeal record : records) {
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            SetmealDto setmealDto = new SetmealDto();
            setmealDto.setCategoryName(categoryName);
            BeanUtils.copyProperties(record, setmealDto);
            setmealList.add(setmealDto);
        }
        map.put("records", setmealList);
        return R.success(map);
    }

    //添加套餐
     @PostMapping
    public R add(@RequestBody SetmealDto setmealDto) {
        setmealService.save(setmealDto);    //保存的是setmealDto从setmeal继承过来的属性对应的值
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        Long setmealDtoId = setmealDto.getId();//获取套餐Id
        for (SetmealDish setmealDish : setmealDishList) {
            setmealDish.setSetmealId(setmealDtoId);
            setmealDishDao.insert(setmealDish);
        }
        return R.success("保存套餐成功！！");
    }

    //删除套餐，判断该套餐是否处于售卖状态
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
       /* LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId, ids).eq(Setmeal::getStatus, 0);
        boolean flag = setmealService.remove(wrapper);
        if (flag) {
            LambdaQueryWrapper<SetmealDish> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.in(SetmealDish::getSetmealId, ids);
            setmealDishDao.delete(wrapper2);
            return R.success("套餐删除成功");
        }

        return R.error("套餐销售状态，不支持删除");*/
        boolean flag = setmealService.delete(ids);
        if (flag) {
            return R.success("套餐删除成功");
        }
        return R.error("在售状态不支持删除");

    }

    //    起售/停售套餐
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable String status, @RequestParam List<Long> ids) {
        //update setmeal set status = {status} where id in(1,2,3)
        LambdaUpdateWrapper<Setmeal> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Setmeal::getStatus, status).in(Setmeal::getId, ids);
        setmealService.update(wrapper);
        return R.success("操作成功");
    }

    //根据套餐id查询套餐的菜品，包括在售和停售（后台）
    @GetMapping("/{id}")
    public R selectById(@PathVariable Long id) {
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        //根据setmealId获取菜品数据
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, id);
        //查出当前套餐下的菜品
        List<SetmealDish> setmealDishList = setmealDishDao.selectList(wrapper);
        //封装的setmealDto中
        setmealDto.setSetmealDishes(setmealDishList);
        return R.success(setmealDto);
    }

    //修改套餐信息
    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R update(@RequestBody SetmealDto setmealDto) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto, setmeal);
        setmealService.updateById(setmeal);
        //先删除当前套餐中的菜品
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        //获取套餐id
        Long setmealId = setmealDto.getId();
        //delete from setmealDish where setmealId = ?
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, setmealId);
        setmealDishDao.delete(wrapper);
        //全部删除后在做添加操作
        //获取setmealId，给setmealDish中的setmealId赋值
        for (SetmealDish setmealDish : setmealDishList) {
            setmealDish.setSetmealId(setmealId);
            setmealDishDao.insert(setmealDish);
        }
        return R.success("修改套餐成功");
    }

    //根据套餐id查询套餐下的菜品，只显示在售（前台）
    @GetMapping("/list")
    @Cacheable(value = "setmealCache" ,key = "#categoryId + '_' + #status")
    public R selectByStatus(Long categoryId, Long status) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getCategoryId, categoryId).eq(Setmeal::getStatus, status);
        List<Setmeal> list = setmealService.list(wrapper);
        return R.success(list);
    }

    /**
     * 查看套餐菜品
     */
    @GetMapping("/dish/{id}")
    public R selectSetmeal(@PathVariable Long id) {
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishDao.selectList(qw);
        for (SetmealDish setmealDish : list) {
            Long dishId = setmealDish.getDishId();
            Dish dish = dishService.getById(dishId);
            String image = dish.getImage();
            setmealDish.setImage(image);
        }
        return R.success(list);
    }
}
